from flask import Flask, jsonify, request
from flask_cors import CORS
from db import (
    get_vocab_grammar_questions,
    get_dialogue_cloze_questions,
    get_reading_questions,
    get_writing_topics,
    submit_answer,
    get_wrong_answers,
    save_wrong_answer,
    delete_wrong_answer,
    clear_wrong_answers,
    get_user_progress,
    save_user_progress
)

app = Flask(__name__)
CORS(app)  # 启用CORS

# ========== 题目数据API ==========
@app.route('/questions/vocabulary-grammar', methods=['GET'])
def get_vocabulary_grammar():
    questions = get_vocab_grammar_questions()
    return jsonify(questions)

@app.route('/questions/dialogue-cloze', methods=['GET'])
def get_dialogue_cloze():
    questions = get_dialogue_cloze_questions()
    return jsonify(questions)

@app.route('/questions/reading', methods=['GET'])
def get_reading():
    passages = get_reading_questions()
    return jsonify(passages)

@app.route('/questions/writing', methods=['GET'])
def get_writing():
    topics = get_writing_topics()
    return jsonify(topics)

# ========== 用户数据API ==========
@app.route('/answers/submit', methods=['POST'])
def submit_answer_api():
    data = request.json
    success = submit_answer(data)
    return jsonify({"success": success, "message": "答案已提交"})

@app.route('/users/<string:user_id>/wrong-answers', methods=['GET'])
def get_user_wrong_answers(user_id):
    wrong_answers = get_wrong_answers(user_id)
    # 转换数据库格式为API要求的格式
    formatted = []
    for wa in wrong_answers:
        formatted.append({
            "id": wa["question_id"],
            "question": wa["question"],
            "options": [{"id": opt_id, "text": opt_text} for opt_id, opt_text in enumerate(wa["options"], start=65)],  # 假设options是列表
            "correctAnswer": wa["correct_answer"],
            "explanation": wa["explanation"],
            "userAnswer": wa["user_answer"],
            "type": wa["question_type"]
        })
    return jsonify(formatted)

@app.route('/users/<string:user_id>/wrong-answers', methods=['POST'])
def save_user_wrong_answer(user_id):
    data = request.json
    data["userId"] = user_id  # 补充用户ID
    success = save_wrong_answer(data)
    return jsonify({"success": success, "message": "错题已保存"})

@app.route('/users/<string:user_id>/wrong-answers/<int:question_id>', methods=['DELETE'])
def delete_user_wrong_answer(user_id, question_id):
    success = delete_wrong_answer(user_id, question_id)
    return jsonify({"success": success, "message": "错题已删除"})

@app.route('/users/<string:user_id>/wrong-answers/clear', methods=['DELETE'])
def clear_user_wrong_answers(user_id):
    success = clear_wrong_answers(user_id)
    return jsonify({"success": success, "message": "错题本已清空"})

@app.route('/users/<string:user_id>/progress', methods=['GET'])
def get_user_progress_api(user_id):
    progress = get_user_progress(user_id)
    # 转换数据库格式为API要求的格式（假设数据库存储为JSONB）
    return jsonify({
        "vocabularyGrammar": progress.get("vocabulary_grammar", {}),
        "dialogueCloze": progress.get("dialogue_cloze", {}),
        "reading": progress.get("reading", {}),
        "writing": progress.get("writing", {})
    })

@app.route('/users/<string:user_id>/progress', methods=['POST'])
def save_user_progress_api(user_id):
    progress_data = request.json
    success = save_user_progress(user_id, progress_data)
    return jsonify({"success": success, "message": "进度已保存"})

if __name__ == '__main__':
    app.run(debug=True, port=5000)